// @algorithm @lc id=1000313 lang=typescript
// @title P5rCT8
// @test([2,1,3],1)  result: null ,expect: 2
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function inorderSuccessor(root: TreeNode | null, p: TreeNode | null): TreeNode | null {
  // 中序遍历
  const inorder = (node: TreeNode | null) => {
    if (node === null) return null;
    let res = inorder(node.left);
    if (res) return res;
    if (pre === p) return node;
    pre = node;
    res = inorder(node.right);
    if (res) return res;
    return null;
  };
  let pre = null;
  return inorder(root);
}
